package com.cy.milktea.service.impl;

import com.cy.milktea.common.annotation.SetUserAndTime;
import com.cy.milktea.mapper.DrinkEntremetsMapper;
import com.cy.milktea.mapper.DrinkMapper;
import com.cy.milktea.pojo.Drink;
import com.cy.milktea.pojo.Entremets;
import com.cy.milktea.service.DrinkService;
import com.cy.milktea.utils.ImageUtils;
import com.cy.milktea.utils.PageHelperUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


@Service
public class DrinkServiceImpl implements DrinkService {

    @Autowired
    private DrinkMapper drinkMapper;
    @Autowired
    private DrinkEntremetsMapper drinkEntremetsMapper;

    @SetUserAndTime
    @Transactional(rollbackFor = Exception.class)//防止io异常不回滚
    @Override
    public int add(Drink drink) throws IOException {
        String imageUrl = null;
        //判断是否为添加新杯号操作
        if (drink.getId() != null
                && StringUtils.hasLength(drink.getImage())
                && StringUtils.hasLength(drink.getCupSize())) {
            //判断杯号是否已经存在
            if (drinkMapper.selectByNameAndCupSize(drink.getName(), drink.getCupSize()) > 0) {
                throw new RuntimeException("添加失败,当前杯号已存在!");
            }
            imageUrl = ImageUtils.cloneImage(drink.getImage());
        } else {
            imageUrl = ImageUtils.saveImage(drink.getFile());
        }
        drink.setImage(imageUrl);
        try {
            //list转换成Json字符串
            drink.tempstToJsonStr();
            drink.sweetnessListToJsonStr();
            //添加drink并将自增的id注入到drink.id
            drinkMapper.insert(drink);
            //添加和tb_entremets表之间的关系
            if (drink.getEntremetsIds() != null && !CollectionUtils.isEmpty(drink.getEntremetsIds())) {
                drinkEntremetsMapper.insert(drink.getId(), drink.getEntremetsIds());
            }
        } catch (Exception e) {
            ImageUtils.deleteImage(imageUrl);
            throw e;
        }
        return 1;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int delete(Integer id) {
        //删除图片
        String image = drinkMapper.selectImageById(id);
        ImageUtils.deleteImage(image);
        //删除和tb_entremets表的关系
        drinkEntremetsMapper.deleteByDrinkId(id);
        return drinkMapper.delete(id);
    }

    @SetUserAndTime(value = "modify")
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int update(Drink drink) {
        if (!CollectionUtils.isEmpty(drink.getEntremetsIds())) {
            //删除旧的和tb_entremets表的关系
            drinkEntremetsMapper.deleteByDrinkId(drink.getId());
            //添加新的和tb_entremets表的关系
            drinkEntremetsMapper.insert(drink.getId(), drink.getEntremetsIds());
        }
        if (!CollectionUtils.isEmpty(drink.getTemps())) {
            drink.tempstToJsonStr();
        }
        if (!CollectionUtils.isEmpty(drink.getSweetnessList())) {
            drink.sweetnessListToJsonStr();
        }
        //判断是否更新图片
        if (drink.getFile() != null && StringUtils.hasLength(drink.getImage())){
            //旧图片地址
            String oldImageUrl = drink.getImage();
            //生成新图片
            String newImageUrl = ImageUtils.saveImage(drink.getFile());
            drink.setImage(newImageUrl);
            try {
                //更新
                if(drinkMapper.update(drink) != 1) throw new RuntimeException("更新失败!");
                //更新成功删除旧图片
                ImageUtils.deleteImage(oldImageUrl);
            } catch (Exception e) {
                //更新失败删除新图片
                ImageUtils.deleteImage(newImageUrl);
                throw e;
            }
        }

            return drinkMapper.update(drink);
    }


    @Override
    public PageHelperUtils.PageInfo<Drink> query(String name, Integer status) {
        //按name和状态查询初始数据
        List<Drink> originalDrinkList = drinkMapper.selectByNameAndStatus(name, status);
        //数据分页
        PageHelperUtils.PageInfo<Drink> drinkPageInfo = PageHelperUtils.startPage(originalDrinkList);
        //对余下的drink进行转换
        List<Drink> drinkList = drinkPageInfo.getList();
        drinkList.forEach(drink -> {
            //可选温度和可选甜度的json字符转换成list列表
            drink.tempJsonStrToList();
            drink.sweetnessJsonStrToList();
            //生成entremetsIds列表
            List<Integer> entremetsIds = new ArrayList<>();
            List<Entremets> entremetsList = drink.getEntremetsList();
            for (Entremets entremets : entremetsList) {
                entremetsIds.add(entremets.getId());
            }
            drink.setEntremetsIds(entremetsIds);
        });
        return drinkPageInfo;
    }


}
